package com.project.controller;

import com.alibaba.fastjson.JSONObject;
import com.project.annotation.IgnoreToken;
import com.project.bean.UserBean;
import com.project.service.IUserService;
import com.project.util.JwtUtil;
import com.project.util.codingUtils.StringUtil;
import com.project.vo.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.net.URI;

/**
 * Created by 卢泓佚  414814103@qq.com on 2021/9/23
 * 微信登录接口
 */
@RestController
@Slf4j
@Api(tags = "微信登录测试接口")
public class WeChatLoginController extends ApiBaseController {
    @Autowired
    private IUserService userService;

    @GetMapping("/login/{code}")
    @ApiOperation(value = "按微信小程序生成的code登录")
    @IgnoreToken
    private R login(@PathVariable("code") String code, HttpServletRequest request) throws Exception {

        // 创建Httpclient对象（同一个code只能访问一次，且5分钟后失效）
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        String url = "https://api.weixin.qq.com/sns/jscode2session?" +
                "appid=" + StringUtil.APP_ID +
                "&secret=" + StringUtil.APP_SECRET +
                "&js_code=" + code + "&grant_type=authorization_code";
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 解析json
        JSONObject jsonObject = (JSONObject) JSONObject.parse(resultString);
        String session_key = jsonObject.get("session_key") + "";
        String openid = jsonObject.get("openid") + "";
        if ("null".equals(openid)) {
            return R.error().message(resultString);
        }
        //从数据库中(或者redis中)查询该登录者是否已经注册,如果没有注册则注册一个新用户。
        UserBean userBean = userService.findByOpenid(openid);
        //将用户绑定在session当中，以便后续跟踪用户状态
        request.getSession().setAttribute("loginUser", userBean);
        // 将openid加密
        UserBean userClone = userBean.clone();
        String secret = JwtUtil.createToken(userClone);
        userClone.setOpenid(secret);
        return R.ok().data("userBean", userClone);
    }

}
